package yxy.game.pm2.module.daily;

import java.util.Collection;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.signtask;
import yxy.cherry.data.bean.signtaskreward;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.message.TaskMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.task.TaskHandle;

public class DailyHandle {

	public Result reward(String playerCode, String taskCode, TaskMessage.DailyTaskProgressBonusReceiveResponse.Builder response) {
		DailyModule module = DailyModule.get(playerCode);
		try {
			if (Task.lockTask(playerCode) && module.tryLock()) {
				for (String code : module.getTaskCodes()) {
					if (code.equals(taskCode)) {
						Task task = Task.get(playerCode, taskCode);
						if (!task.isFinish() || task.isReward()) {
							return Result.TaskCantReward;// 任务奖励不能领取
						}
						Collection<Currency> rewards = new TaskHandle().rewardTask(playerCode, CCReason.每日任务, task);

						signtask data = DataCenter.getData(task.getDataId(), signtask.class);
						module.addexp(data.getExp());

						response.setCode(taskCode);
						response.addAllRewards(new CurrencyHandle().packItems(rewards));

						return Result.Success;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.DataError;
		} finally {
			Task.unlockTask(playerCode);
			module.unlock();
		}
		return Result.ParamError;
	}

	public Result levelReward(String playerCode, int id, TaskMessage.DailyTaskVitalityBonusReceiveResponse.Builder response) {
		DailyModule module = DailyModule.get(playerCode);
		for (Integer rewardedId : module.getLevelReward()) {
			if (rewardedId == id) {
				// 已经领过了
				return Result.DailyTaskBoxRewarded;// 奖励已领过
			}
		}
		signtaskreward data = DataCenter.getData(id, signtaskreward.class);
		if (module.getExp() < data.getCondition()) {
			// 条件不足
			return Result.DailyTaskBoxCantReward;// 奖励不能领取
		}

		try {
			if (module.tryLock()) {
				Collection<Currency> rewards = Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum());
				new CurrencyHandle().addCurrency(playerCode, CCReason.每日任务, rewards);

				response.addAllRewards(new CurrencyHandle().packItems(rewards));

				module.getLevelReward().add(id);
				module.set();

				return Result.Success;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			module.unlock();
		}
		return Result.DataError;
	}
}
